# coding:utf-8
"""
@Version: V1.0
@Author: willson
@License: Apache Licence
@Contact: willson.wu@goertek.com
@Site: goertek.com
@Software: PyCharm
@File: ad.py
@Time: 2019/7/16 20:06
"""

import base64
import json
import re

import requests


class Goertek():
    def __init__(self, name):
        self.employeeID = None
        self.username = None
        self.password = None
        self._getInfo(name)
        pass

    def _getInfo(self, name):
        params = {"curADUser": name, "pwd": "pwd"}
        host = "10.10.20.33"
        c = requests.get("http://{}/Home/userAuth".format(host), params=params)
        a = json.loads(c.text)
        if a["message"] == "ok" and a["success"] == True:
            loginCode = a["loginCode"]
            # loginCode = "ce0f0152-d27c-4755-89b9-e10c57f9f3f2"
            params = {"logincode": "GOERTEK@{}".format(loginCode), "app": "EhrSys"}
            c = requests.get("http://{}/Home/getUserMappingInfo".format(host), params=params)
            a = json.loads(c.text)
            if a["message"] == "ok" and a["success"] == "1":
                self.employeeID = a["data"]["employeeID"]
                self.username = a["data"]["username"]
                self.password = a["data"]["password"]

    def showInfo(self):
        print("工号:", self.employeeID)
        print("用户名:", self.username)
        print("密码:", self.password)

    def getHr(self, isImage=False, isPdf=False):
        name = self.username
        pwd = self.password
        employeeID = self.employeeID

        session = requests.Session()
        c = session.post("http://ehr.goertek.com/psp/ps/EMPLOYEE/HRMS/?cmd=login&languageCd=ZHS",
                         data={"userid": name, "pwd": pwd, "login": "登入"})
        d = session.get(
            "http://ehr.goertek.com/psc/ps/EMPLOYEE/HRMS/s/WEBLIB_GD_PT.ISCRIPT1.FieldFormula.IScript_Ep_ResumeShow?reqHtml=GD_PT_RESUME")
        # print(d.text)
        if isImage:
            re_date_img = re.findall(r"data:image[\S|\W\\s\\S]*?width", d.text)
            if len(re_date_img) != 0:
                date_img = re_date_img[0][22:-7]
                imgdata = base64.b64decode(date_img)
                with open("{}_{}.jpg".format(employeeID, name), mode="wb")as f:
                    f.write(imgdata)
        if isPdf:
            e = session.get(
                "http://ehr.goertek.com/psc/ps/EMPLOYEE/HRMS/c/GD_MENU.GD_PRINT_TRANS_CMP.GBL?printType=RS&emplId={}".format(
                    employeeID))
            pdf_url = re.findall(r"[a-zA-z]+://[^\s]*.pdf", e.text)[0]
            ret = session.get(pdf_url)
            with open("{}_{}.pdf".format(employeeID, name), mode="wb")as f:
                f.write(ret.content)


if __name__ == '__main__':
    # while True:
    #     name = input("请输入用户名:")
    # getInfo(name)

    g = Goertek("edith.huang")
    g.showInfo()
    g.getHr(isImage=True, isPdf=True)
